package leetcode.programmer;

import java.util.HashMap;
import java.util.Map;

// 面试题 01.06. 字符串压缩
public class CompressString {

    public static void main(String[] args) {
        System.out.println(compressString("aabcccccaaa"));
    }

    public static String compressString(String s) {
        int p = 0;
        int q = 0;
        int count = 0;
        StringBuilder res = new StringBuilder();
        while (p < s.length() && q < s.length()) {
            if (s.charAt(p) == s.charAt(q)) {
                count++;
                q++;
            } else {
                res.append(s.charAt(p)).append(count);
                count = 0;
                p = q;
            }
            if (q >= s.length()) {
                res.append(s.charAt(p)).append(count);
            }
        }
        return res.length() >= s.length() ? s : res.toString();
    }
    // 同样是双指针。连续滑动q指针

    public static String compressString2(String s) {
        int p = 0;
        int q = 0;
        StringBuffer stringBuffer = new StringBuffer();
        while (q < s.length()) {

            while (q < s.length() && s.charAt(p) == s.charAt(q)) {
                q++;
            }
            // 不相同了
            stringBuffer.append(s.charAt(p)).append(q-p);
            p=q;
        }
        return s.length()<=stringBuffer.length()?s:stringBuffer.toString();
    }

}
